package db_load;

import static java.lang.System.out;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class Contacts {
	int id;
	String userid;
	String fname;
	String lname;
	String email;
	String country;
	Integer age;
	String phone;
	
	public static List<Contacts> contacts = new ArrayList<Contacts>();
	
	public Contacts(int id, String userid, String fname, String lname,
			String email, Integer age, String phone, String country) {
		
		this.id = id;
		this.userid = userid;
		this.fname = fname;
		this.lname = lname;
		this.email = email;
		this.country = country;
		this.age = age;
		this.phone = phone;
		
		contacts.add(this);
		
	}

	public static List<Contacts> getContactsList(){
		return contacts;
	}
	
	public static void read() {
		String dataRow = null;
		String[] contact = null;

		try (BufferedReader csvFile = new BufferedReader(new FileReader(
				"D:/db/sqlite/contacts.csv"))) {
			
			// ignore first line
			csvFile.readLine();
			
			while ((dataRow = csvFile.readLine()) != null) {
				
				contact = setNullValues(dataRow.split(","));
				
				out.print(contact[0] + ",");
				out.print(contact[1]+ ",");
				out.print(contact[2]+ ",");
				out.print(contact[3]+ ",");
				out.print(contact[4]+ ",");
				out.print(contact[5]+ ",");
				out.print(contact[6]+ ",");
				out.print(contact[7]+ "\n");
				
				Integer _id = Integer.parseInt(contact[0]);
				Integer _age = getNullNumber(contact[5]);
				
				new Contacts(_id, contact[1], contact[2],contact[3],contact[4], _age, contact[6], contact[7]);
						
			}
		} catch (FileNotFoundException ex) {
			out.println(ex);
		} catch(IOException ex){
			out.println(ex);
		}
	}
	
	public void print(){
		out.print(id + ",");
		out.print(userid + ",");
		out.print(fname + ",");
		out.print(lname + ",");
		out.print(email + ",");
		out.print(country + ",");
		out.print(age + ",");
		out.print(phone);
	}
	
	private static String getNullString(String s){
		if (s == null) {
			return "";
		}else {
			return s;
		}
	}
	
	private static Integer getNullNumber(String s){
		if (s == null || "".equals(s)){
			return null;
		}else {
			return Integer.parseInt(s);
		}
	}
	private static String[] setNullValues(String[] s){
		String[] _contact = new String[8];
		
		// Copy Non null values
		_contact[0] = s[0];
		_contact[1] = s[1];
		_contact[2] = s[2];
		_contact[3] = s[3];
		_contact[5] = s[5]; // age
		_contact[7] = s[7];
		
		// Set Null values
		_contact[4] = getNullString(s[4]); // email
		_contact[6] = getNullString(s[6]); // phone
		
		return _contact;
	}
}
